//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package cfca.seal.front.service.ws.impl;

import cfca.sadk.algorithm.common.PKCS7SignedData;
import cfca.sadk.algorithm.sm2.SM2PrivateKey;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.lib.crypto.Session;
import cfca.sadk.util.Base64;
import cfca.sadk.util.CertUtil;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.util.Signature;
import cfca.sadk.x509.certificate.X509CRL;
import cfca.sadk.x509.certificate.X509Cert;
import cfca.seal.bean.AdminUser;
import cfca.seal.bean.OperationLog;
import cfca.seal.bean.Organization;
import cfca.seal.bean.Seal;
import cfca.seal.bean.SealCert;
import cfca.seal.bean.SealImage;
import cfca.seal.bean.SealUser;
import cfca.seal.bean.User;
import cfca.seal.dao.main.IAdminUserDao;
import cfca.seal.dao.main.IOperationLogDao;
import cfca.seal.dao.main.IOrganizationDao;
import cfca.seal.dao.main.ISealCertDao;
import cfca.seal.dao.main.ISealDao;
import cfca.seal.dao.main.ISealImageDao;
import cfca.seal.dao.main.IUserDao;
import cfca.seal.exception.CodeException;
import cfca.seal.front.service.FunctionType;
import cfca.seal.front.service.ws.IAssistSealService;
import cfca.seal.front.service.ws.bean.AutoGenerateImageBean;
import cfca.seal.front.service.ws.bean.MakeAndBindClientSealBean;
import cfca.seal.front.service.ws.bean.SignBean;
import cfca.seal.front.service.ws.bean.VerifyBean;
import cfca.seal.front.service.ws.util.ValidityUtil;
import cfca.seal.maker.util.SealExtracter;
import cfca.seal.mananger.CrlManager;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.mananger.SealCertManager;
import cfca.seal.mananger.SealManager;
import cfca.seal.mananger.TrustCertManager;
import cfca.seal.sadk.DonePdfSeal;
import cfca.seal.sadk.LocationInfo;
import cfca.seal.sadk.PrePdfReader;
import cfca.seal.sadk.SignatureLandscape;
import cfca.seal.system.Env;
import cfca.seal.util.EncryptUtil;
import cfca.seal.util.ImageUtil;
import cfca.seal.util.JHARDUtil;
import cfca.seal.util.OutPicture;
import cfca.seal.util.SealCertUtil;
import cfca.seal.util.StringUtil;
import cfca.seal.util.TimeUtil;
import cfca.seal.util.VerifyUtil;
import com.lowagie.text.pdf.PdfReader;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AssistSealServiceImpl implements IAssistSealService {
  private static final int SEAL_TYPE_PERSONAL = 1;
  private static final Logger logger = LoggerFactory.getLogger("service_sys");
  @Resource
  ISealDao dao;
  @Resource
  ISealCertDao sealCertdao;
  @Resource
  ISealImageDao modeldao;
  @Resource
  IAdminUserDao managerdao;
  @Resource
  IOrganizationDao orgdao;
  @Resource
  IUserDao userdao;
  @Resource
  IOperationLogDao operationLogDao;

  public AssistSealServiceImpl() {
  }

  public String p7SignDetached(byte[] source, String signStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.p7SignDetached.toString(), "P7分离式签名");
    byte[] result = "".getBytes();
    String resultValue = "";
    String orgId = "";
    StringBuffer buffer = new StringBuffer();

    String sealBean;
    try {
      SignBean signBean = new SignBean(signStrategyXML);
      ValidityUtil.checkParamForSign(signBean);
      operationLog.setObjectId(signBean.getSealCode());
      logger.info("P7签名：签名人:" + signBean.getSealPerson() + ",印章code:" + signBean.getSealCode() + ",签名地点:" + signBean.getSealLocation() + ",签名理由:" + signBean.getSealReason() + ",开始。");
      if (null == source || source.length == 0) {
        throw new CodeException("C3007", "PDF文档不能为空");
      }

      sealBean = null;
      Seal seal;
      if ("sqlite".equals(Env.databaseType)) {
        seal = SealManager.getInstance().getSealByCode(signBean.getSealCode());
      } else {
        seal = this.dao.getSealByCode(signBean.getSealCode());
      }

      this.validateParamsSign(signBean.getSealPassword(), seal);
      orgId = seal.getOrganizationId();
      Session session = null;
      PrivateKey priKey = null;
      X509Cert cert = null;
      String signAlg = "sha1WithRSAEncryption";
      if (seal.getCertType() == 0) {
        JCrypto.getInstance().initialize("JSOFT_LIB", (Object)null);
        session = JCrypto.getInstance().openSession("JSOFT_LIB");
        SealExtracter sEx = new SealExtracter(seal.getSealData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
        int keyType = sEx.getKeyType();
        if (1 == keyType) {
          priKey = KeyUtil.getPrivateKeyFromPFX(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
          cert = CertUtil.getCertFromPFX(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
        } else if (2 == keyType) {
          priKey = KeyUtil.getPrivateKeyFromSM2(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
          cert = CertUtil.getCertFromSM2(seal.getSealPfxData());
          signAlg = "sm3WithSM2Encryption";
        }
      } else if (seal.getCertType() == 1 || seal.getCertType() == 2) {
        SealCert sealCert = null;
        if ("sqlite".equals(Env.databaseType)) {
          sealCert = SealCertManager.getInstance().getSealById(seal.getSealCertId());
        } else {
          sealCert = this.sealCertdao.getSealCertById(seal.getSealCertId());
        }

        JCrypto.getInstance().initialize(sealCert.getDevice(), (Object)null);
        session = JCrypto.getInstance().openSession(sealCert.getDevice());
        if ("JSOFT_LIB".equals(sealCert.getDevice())) {
          sealCert.decryptCiphertext(sealCert);
          if ("SHA1RSA".equals(sealCert.getCertAlg())) {
            priKey = (PrivateKey)SealCertUtil.getRSAPrivateKey(Base64.decode(sealCert.getPrivateKeyData()));
          } else {
            priKey = SM2PrivateKey.getInstance(Base64.decode(sealCert.getPrivateKeyData()));
          }
        } else {
          priKey = JHARDUtil.getPrivateKeyFromHard(sealCert.getKeyId(), session);
        }

        cert = new X509Cert(sealCert.getPublickCertData());
      }

      Signature signUtil = new Signature();
      result = signUtil.p7SignMessageDetach(signAlg, source, (PrivateKey)priKey, cert, session);
      resultValue = "<Result><Code>200</Code><Message>successfully!</Message><Signature>" + Base64.toBase64String(result) + "</Signature></Result>";
      logger.info("P7签名：签名人:" + signBean.getSealPerson() + ",印章code:" + signBean.getSealCode() + ",签名地点:" + signBean.getSealLocation() + ",签名理由:" + signBean.getSealReason() + ",结束。");
      return resultValue;
    } catch (CodeException var20) {
      operationLog.setResult(10);
      logger.error("接口在进行P7签名发生系统异常! ", var20);
      buffer.append("<Result><Code>" + var20.getCode() + "</Code><Message>" + var20.getMessage() + "</Message></Result>");
      sealBean = buffer.toString();
    } catch (Exception var21) {
      operationLog.setResult(10);
      logger.error("接口在进行P7签名发生系统异常! ", var21);
      buffer.append("<Result><Code>C0001</Code><Message>接口在进行P7签名发生系统异常!</Message></Result>");
      sealBean = buffer.toString();
      return sealBean;
    } finally {
      operationLog.setOrganizationId(orgId);
      this.operationLogDao.insert(operationLog);
    }

    return sealBean;
  }

  private void validateParamsSign(String sealPwd, Seal sealBean) throws Exception {
    if (sealBean == null) {
      throw new CodeException("C4004", "没有找到对应的印章");
    } else if (1 != sealBean.getStatus()) {
      throw new CodeException("C4005", "印章未启用");
    } else if (-1 == sealBean.getCertType()) {
      throw new CodeException("C4006", "无证书印章，无法签章/签名");
    } else if (!EncryptUtil.decrypto(sealBean.getSealPwd()).equals(sealPwd)) {
      throw new CodeException("C1002", "印章密码不正确");
    } else {
      this.CheckIsValidateCert(sealBean);
    }
  }

  public String p7VerifyDetached(String signatureBase64, byte[] source, String verifyStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.p7VerifyDetached.toString(), "P7分离式验签");
    logger.info("P7分离式验签,开始");
    logger.info("验签策略：" + verifyStrategyXML);
    boolean verify = false;
    String certInfo = "";
    StringBuffer buffer = new StringBuffer();

    String var9;
    try {
      VerifyBean verifyBean = new VerifyBean(verifyStrategyXML);
      ValidityUtil.checkParamForVerify(verifyBean);
      if (StringUtil.isEmpty(signatureBase64)) {
        throw new CodeException("C3013", "签章结果不能为空");
      }

      if (null == source || source.length == 0) {
        throw new CodeException("C3041", "签章原文不能为空");
      }

      Signature signUtil = new Signature();
      JCrypto.getInstance().initialize("JSOFT_LIB", (Object)null);
      Session session = JCrypto.getInstance().openSession("JSOFT_LIB");
      verify = signUtil.p7VerifyMessageDetach(source, Base64.decode(signatureBase64), session);
      if (!verify) {
        throw new CodeException("C3022", "验证签章的PDF签名失败");
      }

      PKCS7SignedData pkcs7 = new PKCS7SignedData(session);
      pkcs7.loadBase64(Base64.decode(signatureBase64));
      String p1Base64 = Base64.toBase64String(pkcs7.getSignature());
      X509Cert cert = pkcs7.getSignerX509Cert();
      String dn = cert.getSubject();
      String sn = cert.getStringSerialNumber();
      certInfo = "<CertDN>" + dn + "</CertDN><CertSN>" + sn + "</CertSN><P1Base64>" + p1Base64 + "</P1Base64>";
      int certVerifyType = Integer.parseInt(verifyBean.getVerifyType());
      if (certVerifyType > 0) {
        X509Cert x509Cert = signUtil.getSignerCert();
        List<X509Cert> certs = new ArrayList();
        certs.add(x509Cert);
        if (certVerifyType > 1) {
          List<X509Cert> trustCerts = TrustCertManager.instance.getTrustCertList();
          if (!VerifyUtil.verifyCertSign(certs, trustCerts)) {
            throw new CodeException("C3025", "证书链验证签章的证书签名失败");
          }
        }

        if (certVerifyType > 2) {
          X509CRL x509crl = CrlManager.getX509CRL(StringUtil.formatIssuerKey(x509Cert.getIssuer()));
          if (x509crl == null) {
            throw new CodeException("C3026", "验证签章的证书没有对应的CRL");
          }

          if (VerifyUtil.verifyByCRL(x509Cert, x509crl)) {
            throw new CodeException("C3027", "验证签章的证书存在已经吊销");
          }
        }
      }

      logger.info("P7分离式验签,结束");
      return buffer.append("<Result><Code>200</Code><Message>successfully!</Message>" + certInfo + "</Result>").toString();
    } catch (CodeException var24) {
      operationLog.setResult(10);
      buffer.append("<Result><Code>" + var24.getCode() + "</Code><Message>" + var24.getMessage() + "</Message></Result>");
      logger.error("接口在进行P7验签发生失败!", var24);
      var9 = buffer.toString();
    } catch (Exception var25) {
      operationLog.setResult(10);
      if (var25.getMessage().contains("cfca.sadk.org.bouncycastle.asn1.DERApplicationSpecific cannot be cast to cfca.sadk.org.bouncycastle.asn1.ASN1Sequence")) {
        buffer.append("<Result><Code>C9011</Code><Message>P7签名验证失败</Message></Result>");
      } else {
        buffer.append("<Result><Code>C0001</Code><Message>接口在进行P7验签发生系统异常!</Message></Result>");
      }

      logger.error("接口在进行P7验签发生系统异常!", var25);
      var9 = buffer.toString();
      return var9;
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return var9;
  }

  public String getSealInfo(String sealCode) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.getSealInfo.toString(), "获取印章信息");
    logger.info("获取印章信息，印章编码：" + sealCode + ",开始");

    String sealPerson;
    try {
      ValidityUtil.checkSealCode(sealCode);
      Seal seal = this.dao.getSealByCode(sealCode);
      if (null == seal) {
        throw new CodeException("C4004", "没有找到对应的印章");
      }

      sealPerson = "";
      String sealOrg = "";
      AdminUser manager = this.managerdao.getManagerById(seal.getCreator());
      if (manager != null) {
        sealPerson = manager.getRealName();
      } else {
        sealPerson = seal.getCreator();
      }

      Organization org = this.orgdao.getOrganizationById(seal.getOrganizationId());
      if (org != null) {
        sealOrg = org.getName();
      } else {
        sealOrg = seal.getOrganizationId();
      }

      String result = "<Result><Code>200</Code><Message>successfully!</Message><SealInfoXML><SealPerson>" + sealPerson + "</SealPerson>" + "<SealOrg>" + sealOrg + "</SealOrg>" + "<SealName>" + seal.getName() + "</SealName>" + "<SealCode>" + seal.getCode() + "</SealCode>" + "<Image>" + new String(Base64.encode(seal.getSealImageData()), "UTF-8") + "</Image>" + "</SealInfoXML></Result>";
      logger.info("获取结果：" + result);
      logger.info("获取印章信息，印章编码：" + sealCode + ",结束");
      String var9 = result;
      return var9;
    } catch (CodeException var14) {
      operationLog.setResult(10);
      logger.error("接口在进行印章取得发生异常!", var14);
      sealPerson = "<Result><Code>" + var14.getCode() + "</Code><Message>" + var14.getMessage() + "</Message></Result>";
    } catch (Exception var15) {
      operationLog.setResult(10);
      logger.error("接口在进行印章取得发生系统异常!", var15);
      sealPerson = "<Result><Code>C0001</Code><Message>接口在进行印章取得发生系统异常!</Message></Result>";
      return sealPerson;
    } finally {
      operationLog.setObjectId(sealCode);
      this.operationLogDao.insert(operationLog);
    }

    return sealPerson;
  }

  @Override
  public String autoGenerateImage(String imageStrategyXML) {
    logger.info("自助生成图片开始");
    logger.info("自助生成图片策略：" + imageStrategyXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.autoGenerateImage.toString(), "自助生成图片");
    StringBuffer buffer = new StringBuffer();

    String var5;
    try {
      AutoGenerateImageBean autoGenerateImageBean = new AutoGenerateImageBean(imageStrategyXML);
      ValidityUtil.checkParamForAutoGenerateImage(autoGenerateImageBean);
      byte[] image = "".getBytes();
      int fontSize = Integer.parseInt(autoGenerateImageBean.getFontSize());
      int height = Integer.parseInt(autoGenerateImageBean.getImageHeight());
      int width = Integer.parseInt(autoGenerateImageBean.getImageWidth());
      if ("1".equals(autoGenerateImageBean.getImageShape())) {
        image = OutPicture.getNamePngToByte(autoGenerateImageBean.getImageName(), height, width, fontSize, autoGenerateImageBean.getColor());
      } else if ("2".equals(autoGenerateImageBean.getImageShape())) {
        image = OutPicture.getCirclePngToByte(autoGenerateImageBean.getImageName(), autoGenerateImageBean.getImageName2(), height, width);
      } else if ("3".equals(autoGenerateImageBean.getImageShape())) {
        image = OutPicture.getRectanglePng(autoGenerateImageBean.getImageName(), width, height, fontSize, autoGenerateImageBean.getColor());
      }

      image = ImageUtil.transferAlpha(image);
      buffer.append(Base64.toBase64String(image));
      logger.info("自助生成图片结束");
      return buffer.toString();
    } catch (CodeException var13) {
      operationLog.setResult(10);
      logger.error("接口在进行自动生成印章图片发生系统异常!", var13);
      buffer.append("<Error><ErrorCode>" + var13.getCode() + "</ErrorCode><ErrorMessage>" + var13.getMessage() + "</ErrorMessage></Error>");
      return buffer.toString();
    } catch (Exception var14) {
      operationLog.setResult(10);
      buffer.append("<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>接口在进行自动生成印章图片发生系统异常!</ErrorMessage></Error>");
      logger.error("接口在进行自动生成印章图片发生系统异常!", var14);
      var5 = buffer.toString();
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return var5;
  }

  public String p1Sign(byte[] source, String signStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.p1Sign.toString(), "P1签名");
    String result = "";
    String orgId = "";

    String var8;
    try {
      StringBuffer sealBean;
      try {
        if (null == source || source.length == 0) {
          throw new CodeException("C3007", "PDF文档不能为空");
        }

        SignBean signBean = new SignBean(signStrategyXML);
        operationLog.setObjectId(signBean.getSealCode());
        ValidityUtil.checkParamForSign(signBean);
        sealBean = null;
        Seal seal;
        if ("sqlite".equals(Env.databaseType)) {
          seal = SealManager.getInstance().getSealByCode(signBean.getSealCode());
        } else {
          seal = this.dao.getSealByCode(signBean.getSealCode());
        }

        this.validateParamsSign(signBean.getSealPassword(), seal);
        orgId = seal.getOrganizationId();
        Session session = null;
        PrivateKey priKey = null;
        if (seal.getCertType() == 0) {
          JCrypto.getInstance().initialize("JSOFT_LIB", (Object)null);
          session = JCrypto.getInstance().openSession("JSOFT_LIB");
          SealExtracter sEx = new SealExtracter(seal.getSealData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
          int keyType = sEx.getKeyType();
          if (1 == keyType) {
            priKey = KeyUtil.getPrivateKeyFromPFX(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
          } else if (2 == keyType) {
            KeyUtil.getPrivateKeyFromSM2(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
          }
        } else if (seal.getCertType() == 1 || seal.getCertType() == 2) {
          SealCert sealCert = null;
          if ("sqlite".equals(Env.databaseType)) {
            sealCert = SealCertManager.getInstance().getSealById(seal.getSealCertId());
          } else {
            sealCert = this.sealCertdao.getSealCertById(seal.getSealCertId());
          }

          JCrypto.getInstance().initialize(sealCert.getDevice(), (Object)null);
          session = JCrypto.getInstance().openSession(sealCert.getDevice());
          if ("JSOFT_LIB".equals(sealCert.getDevice())) {
            sealCert.decryptCiphertext(sealCert);
            if ("SHA1RSA".equals(sealCert.getCertAlg())) {
              priKey = (PrivateKey)SealCertUtil.getRSAPrivateKey(Base64.decode(sealCert.getPrivateKeyData()));
            } else {
              priKey = SM2PrivateKey.getInstance(Base64.decode(sealCert.getPrivateKeyData()));
            }
          } else {
            priKey = JHARDUtil.getPrivateKeyFromHard(sealCert.getKeyId(), session);
          }
        }

        Signature signUtil = new Signature();
        byte[] signResult = "".getBytes();
        signResult = signUtil.p1SignMessage("sha1WithRSAEncryption", source, (PrivateKey)priKey, session);
        result = "<Result><Code>200</Code><Message>successfully!</Message><Signature>" + Base64.toBase64String(signResult) + "</Signature></Result>";
        logger.info("P1签名：签名人:" + signBean.getSealPerson() + ",印章编码:" + signBean.getSealCode() + ",签名地点:" + signBean.getSealLocation() + ",签名理由:" + signBean.getSealReason());
        return result;
      } catch (CodeException var16) {
        operationLog.setResult(10);
        logger.error("接口在进行P1签名发生系统异常! ", var16);
        sealBean = new StringBuffer();
        sealBean.append("<Result><Code>" + var16.getCode() + "</Code><Message>" + var16.getMessage() + "</Message></Result>");
        var8 = sealBean.toString();
        return var8;
      } catch (Exception var17) {
        operationLog.setResult(10);
        sealBean = new StringBuffer();
        sealBean.append("<Result><Code>C0001</Code><Message>接口在进行P1签名发生系统异常!</Message></Result>");
        logger.error("接口在进行P1签名发生系统异常! ", var17);
        var8 = sealBean.toString();
      }
    } finally {
      operationLog.setOrganizationId(orgId);
      this.operationLogDao.insert(operationLog);
    }

    return var8;
  }

  @Override
  public String makeAndBindClientSeal(byte[] imageData, String clientSealXML, String userXML, String orgCode) {
    logger.info("客户端制章并绑定接口,开始");
    logger.info("客户端印章策略文件：" + clientSealXML);
    logger.info("用户基本信息：" + userXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.makeAndBindClientSeal.toString(), "客户端制章并绑定");
    String orgId = "";

    String var8;
    try {
      ValidityUtil.checkOrgCode(orgCode);
      Organization org = this.orgdao.getOrganizationByCode(orgCode);
      if (org == null) {
        throw new CodeException("C8002", "机构编码不存在");
      }

      orgId = org.getId();
      MakeAndBindClientSealBean makeAndBindClientSealBean = new MakeAndBindClientSealBean(clientSealXML);
      makeAndBindClientSealBean.setCertDn(StringUtil.getNodeText(userXML, "CertDN"));
      makeAndBindClientSealBean.setCertSn(StringUtil.getNodeText(userXML, "CertSN"));
      makeAndBindClientSealBean.setName(StringUtil.getNodeText(userXML, "Name"));
      makeAndBindClientSealBean.setRealName(StringUtil.getNodeText(userXML, "RealName"));
      ValidityUtil.checkParamForMakeAndBindClientSeal(makeAndBindClientSealBean);
      String userId = StringUtil.generateID();
      String sealUserId = StringUtil.generateID();
      String sealId = StringUtil.generateID();
      Date createTime = new Date();
      Seal seal = new Seal();
      seal.setId(sealId);
      seal.setName(makeAndBindClientSealBean.getSealName());
      seal.setCode(makeAndBindClientSealBean.getSealCode());
      seal.setSealPwd(EncryptUtil.encrypto(makeAndBindClientSealBean.getSealPassword()));
      seal.setOrganizationId(orgId);
      seal.setStatus(1);
      seal.setCertType(-1);
      AdminUser mng = this.managerdao.getManagerByUsername(makeAndBindClientSealBean.getSealPerson());
      if (mng != null) {
        seal.setCreator(mng.getRealName());
      } else {
        seal.setCreator(makeAndBindClientSealBean.getSealPerson());
      }

      Seal aseal = this.dao.getSealByCode(seal.getCode());
      if (aseal != null) {
        throw new CodeException("C1008", "重复的印章编码");
      }

      if (imageData != null && imageData.length != 0) {
        ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
        BufferedImage bImage = ImageIO.read(bais);
        int imagehighet = bImage.getHeight();
        int imagewidth = bImage.getWidth();
        this.saveNoModel(seal, ImageUtil.transferAlpha(imageData), imagehighet, imagewidth, 1);
      } else {
        this.save(seal, makeAndBindClientSealBean.getImageCode());
      }

      logger.info("客户端制章并绑定接口:完成制章!印章编码:" + seal.getCode());
      User user = new User(makeAndBindClientSealBean.getName(), makeAndBindClientSealBean.getRealName(), makeAndBindClientSealBean.getCertSn(), makeAndBindClientSealBean.getCertDn(), orgId, "通过客户端制章并绑定接口维护用户信息", createTime);
      List<User> userList = this.userdao.getUserByCertSn(makeAndBindClientSealBean.getCertSn());
      if (null != userList && userList.size() > 0) {
        User u = (User)userList.get(0);
        user.setId(u.getId());
        this.userdao.update(user);
        logger.info("客户端制章并绑定接口:完成更新用户!");
      } else {
        user.setId(userId);
        this.userdao.insert(user);
        logger.info("客户端制章并绑定接口:完成添加用户!");
      }

      List<String> idList = this.dao.getBindUserId(sealId);
      if (null != idList && idList.contains(user.getId())) {
        logger.info("印章与用户的绑定关系已存在!");
      } else {
        SealUser sealUser = new SealUser(sealUserId, sealId, user.getId(), createTime);
        List<SealUser> list = new ArrayList();
        list.add(sealUser);
        this.dao.bindUser(list);
        logger.info("完成印章绑定用户!用户名称:" + user.getName() + "印章编码:" + seal.getCode());
      }

      logger.info("客户端制章并绑定接口,结束");
      return "<Result><Code>200</Code><Message>successfully!</Message></Result>";
    } catch (CodeException var25) {
      operationLog.setResult(10);
      logger.info("客户端制章并绑定接口发生异常", var25);
      var8 = "<Result><Code>" + var25.getCode() + "</Code><Message>" + var25.getMessage() + "</Message></Result>";
    } catch (Exception var26) {
      operationLog.setResult(10);
      logger.info("客户端制章并绑定接口发生异常", var26);
      var8 = "<Result><Code>C0001</Code><Message>客户端制章并绑定接口发生异常</Message></Result>";
      return var8;
    } finally {
      operationLog.setOrganizationId(orgId);
      this.operationLogDao.insert(operationLog);
    }

    return var8;
  }

  private boolean save(Seal seal, String imageCode) throws CodeException {
    try {
      SealImage model = this.modeldao.getSealModelByModelCode(imageCode);
      if (model == null) {
        throw new CodeException("C3056", "印模不存在");
      } else {
        seal.setType(model.getType());
        seal.setSealImageData(model.getSealImageData());
        seal.setImageHeight(model.getImageHeight());
        seal.setImageWidth(model.getImageWidth());
        return this.dao.insert(seal);
      }
    } catch (CodeException var4) {
      throw new CodeException(var4.getCode(), var4.getMessage());
    } catch (Exception var5) {
      throw new CodeException("C0001", var5.getMessage());
    }
  }

  private boolean saveNoModel(Seal seal, byte[] image, int height, int width, int type) throws CodeException {
    try {
      seal.setType(type);
      seal.setSealImageData(image);
      seal.setImageHeight(height);
      seal.setImageWidth(width);
      return this.dao.insert(seal);
    } catch (CodeException var7) {
      throw new CodeException(var7.getCode(), var7.getMessage());
    } catch (Exception var8) {
      throw new CodeException("C0001", var8.getMessage());
    }
  }

  @Override
  public String getBindedSealInfo(String certDN, String certSN) {
    logger.info("获取绑定印章信息,开始");
    logger.info("绑定印章的DN：" + certDN);
    logger.info("绑定印章的SN：" + certSN);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.getBindedSealInfo.toString(), "获取绑定印章信息");
    StringBuffer sealInfo = new StringBuffer();

    String sealPerson;
    try {
      ValidityUtil.checkParamForGetBindedSealInfo(certDN, certSN);
      List<Seal> sealList = this.dao.getSealByCertDnAndCertSn(certDN, certSN);
      if (null == sealList || sealList.size() == 0) {
        throw new CodeException("C4004", "没有找到对应的印章");
      }

      sealPerson = "";
      String sealOrg = "";

      Seal seal;
      for(Iterator i$ = sealList.iterator(); i$.hasNext(); sealInfo.append("<SealInfo>").append("<SealPerson>").append(sealPerson).append("</SealPerson>").append("<SealOrg>").append(sealOrg).append("</SealOrg>").append("<SealName>").append(seal.getName()).append("</SealName>").append("<SealCode>").append(seal.getCode()).append("</SealCode>").append("<Image>").append(new String(Base64.encode(seal.getSealImageData()), "UTF-8")).append("</Image>").append("</SealInfo>")) {
        seal = (Seal)i$.next();
        AdminUser manager = this.managerdao.getManagerById(seal.getCreator());
        if (manager != null) {
          sealPerson = manager.getRealName();
        } else {
          sealPerson = seal.getCreator();
        }

        Organization org = this.orgdao.getOrganizationById(seal.getOrganizationId());
        if (org != null) {
          sealOrg = org.getName();
        } else {
          sealOrg = seal.getOrganizationId();
        }
      }

      logger.info("印章信息：" + sealInfo);
      logger.info("获取绑定印章信息,结束");
      return "<Result><Code>200</Code><Message>successfully!</Message><List>" + sealInfo.toString() + "</List></Result>";
    } catch (CodeException var16) {
      operationLog.setResult(10);
      logger.info("获取绑定印章信息接口发生异常", var16);
      sealPerson = "<Result><Code>" + var16.getCode() + "</Code><Message>" + var16.getMessage() + "</Message></Result>";
    } catch (Exception var17) {
      operationLog.setResult(10);
      logger.info("获取绑定印章信息接口发生异常", var17);
      sealPerson = "<Result><Code>C0001</Code><Message>获取绑定印章信息接口发生异常</Message></Result>";
      return sealPerson;
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return sealPerson;
  }

  @Override
  public String bindClientSeal(String clientSealCode, String userXML, String orgCode) {
    logger.info("客户端印章绑定接口,开始");
    logger.info("客户端印章编码：" + clientSealCode);
    logger.info("用户基本信息：" + userXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.bindClientSeal.toString(), "客户端印章绑定");
    String orgId = "";

    try {
      String var7;
      try {
        ValidityUtil.checkOrgCode(orgCode);
        Organization org = this.orgdao.getOrganizationByCode(orgCode);
        if (org == null) {
          throw new CodeException("C8002", "机构编码不存在");
        }

        orgId = org.getId();
        MakeAndBindClientSealBean makeAndBindClientSealBean = new MakeAndBindClientSealBean();
        makeAndBindClientSealBean.setCertDn(StringUtil.getNodeText(userXML, "CertDN"));
        makeAndBindClientSealBean.setCertSn(StringUtil.getNodeText(userXML, "CertSN"));
        makeAndBindClientSealBean.setName(StringUtil.getNodeText(userXML, "Name"));
        makeAndBindClientSealBean.setRealName(StringUtil.getNodeText(userXML, "RealName"));
        ValidityUtil.checkParamForBindClientSeal(makeAndBindClientSealBean);
        Seal seal = this.dao.getSealByCode(clientSealCode);
        if (null == seal) {
          throw new CodeException("C4004", "没有找到对应的印章");
        }

        if (-1 != seal.getCertType()) {
          throw new CodeException("C4007", "印章已有证书，无法绑定用户");
        }

        String sealId = seal.getId();
        String userId = StringUtil.generateID();
        String sealUserId = StringUtil.generateID();
        Date createTime = new Date();
        User user = new User(makeAndBindClientSealBean.getName(), makeAndBindClientSealBean.getRealName(), makeAndBindClientSealBean.getCertSn(), makeAndBindClientSealBean.getCertDn(), orgId, "通过客户端印章绑定接口维护用户信息", createTime);
        List<User> userList = this.userdao.getUserByCertSn(makeAndBindClientSealBean.getCertSn());
        if (null != userList && userList.size() > 0) {
          User u = (User)userList.get(0);
          user.setId(u.getId());
          this.userdao.update(user);
          logger.info("客户端印章绑定接口:完成更新用户!");
        } else {
          user.setId(userId);
          this.userdao.insert(user);
          logger.info("客户端印章绑定接口:完成添加用户!");
        }

        List<String> idList = this.dao.getBindUserId(sealId);
        if (null != idList && idList.contains(user.getId())) {
          logger.info("印章与用户的绑定关系已存在!");
        } else {
          SealUser sealUser = new SealUser(sealUserId, sealId, user.getId(), createTime);
          List<SealUser> list = new ArrayList();
          list.add(sealUser);
          this.dao.bindUser(list);
          logger.info("完成印章绑定用户!用户名称:" + user.getName() + "印章编码:" + clientSealCode);
        }

        logger.info("客户端印章绑定接口,结束");
      } catch (CodeException var22) {
        operationLog.setResult(10);
        logger.info("客户端印章绑定接口发生异常", var22);
        var7 = "<Result><Code>" + var22.getCode() + "</Code><Message>" + var22.getMessage() + "</Message></Result>";
        return var7;
      } catch (Exception var23) {
        operationLog.setResult(10);
        logger.info("客户端印章绑定接口发生异常", var23);
        var7 = "<Result><Code>C0001</Code><Message>客户端印章绑定接口发生异常</Message></Result>";
        return var7;
      }
    } finally {
      operationLog.setOrganizationId(orgId);
      this.operationLogDao.insert(operationLog);
    }

    return "<Result><Code>200</Code><Message>successfully!</Message></Result>";
  }

  @Override
  public String getKeywordLocationsInPdf(byte[] pdf, String keyword) {
    logger.info("获取关键字位置,开始");
    logger.info("关键字：" + keyword);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.getKeywordLocationsInPdf.toString(), "获取关键字位置");
    StringBuffer sb = new StringBuffer("");

    try {
      String var6;
      try {
        if (StringUtil.isEmpty(keyword)) {
          throw new CodeException("C3042", "关键字没有输入");
        } else if (null != pdf && pdf.length != 0) {
          PdfReader pdfReader = new PdfReader(pdf);
          System.out.println("PDF文档的宽度: " + pdfReader.getPageSize(1).getWidth());
          System.out.println("PDF文档的高度: " + pdfReader.getPageSize(1).getHeight());
          DonePdfSeal donePdfSeal = new DonePdfSeal();
          PrePdfReader prePdfReader = new PrePdfReader(pdf);
          donePdfSeal.initPdfReader(prePdfReader);
          donePdfSeal.updateLocationInfoByKeyword(keyword);
          LocationInfo locationInfo = donePdfSeal.getLocationInfo();
          if (locationInfo != null && locationInfo.getLocSignatureLandscapeInfoList().size() > 0) {
            List<SignatureLandscape> list = locationInfo.getLocSignatureLandscapeInfoList();

            for(int i = 0; i < list.size(); ++i) {
              int pageNo = ((SignatureLandscape)list.get(i)).page;
              int lx = (int)((SignatureLandscape)list.get(i)).rect.getLeft();
              int ly = (int)((SignatureLandscape)list.get(i)).rect.getBottom();
              int height = (int)prePdfReader.getPdfReader().getPageSize(pageNo).getHeight();
              int width = (int)prePdfReader.getPdfReader().getPageSize(pageNo).getWidth();
              sb.append("<Location>").append("<PageNo>").append(pageNo).append("</PageNo>").append("<LX>").append(lx).append("</LX>").append("<LY>").append(ly).append("</LY>").append("<Width>").append(width).append("</Width>").append("<Height>").append(height).append("</Height>").append("</Location>");
            }

            logger.info("获取关键字位置,结束");
            return "<Result><Code>200</Code><Message>successfully!</Message><List>" + sb.toString() + "</List></Result>";
          } else {
            throw new CodeException("C1010", "没有找到相应的关键字：" + keyword);
          }
        } else {
          throw new CodeException("C3007", "PDF文档不能为空");
        }
      } catch (CodeException var20) {
        operationLog.setResult(10);
        logger.info("获取关键字位置接口发生异常", var20);
        var6 = "<Result><Code>" + var20.getCode() + "</Code><Message>" + var20.getMessage() + "</Message></Result>";
        return var6;
      } catch (Exception var21) {
        operationLog.setResult(10);
        logger.info("获取关键字位置接口发生异常", var21);
        if (var21.getMessage().contains("not found")) {
          var6 = "<Result><Code>C1010</Code><Message>没有找到相应的关键字</Message></Result>";
          return var6;
        } else {
          var6 = "<Result><Code>C0001</Code><Message>获取获取关键字位置接口发生异常</Message></Result>";
          return var6;
        }
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }
  }

  private void CheckIsValidateCert(Seal sealBean) throws Exception {
    X509Cert x509Cert = null;
    if (0 == sealBean.getCertType()) {
      SealExtracter sEx = new SealExtracter(sealBean.getSealData(), EncryptUtil.decrypto(sealBean.getSealPfxPwd()));
      int keyType = sEx.getKeyType();
      if (1 == keyType) {
        x509Cert = CertUtil.getCertFromPFX(sealBean.getSealPfxData(), EncryptUtil.decrypto(sealBean.getSealPfxPwd()));
      } else if (2 == keyType) {
        x509Cert = CertUtil.getCertFromSM2(sealBean.getSealPfxData());
      }
    } else if (2 == sealBean.getCertType() || 1 == sealBean.getCertType()) {
      SealCert sealCert = this.sealCertdao.getSealCertById(sealBean.getSealCertId());
      x509Cert = new X509Cert(sealCert.getPublickCertData());
    }

    if (!VerifyUtil.verifyCertDate(x509Cert, TimeUtil.getCurrentTime())) {
      throw new CodeException("C9001", "证书已过期或者还未生效");
    } else {
      X509CRL x509crl = CrlManager.getX509CRL(StringUtil.formatIssuerKey(x509Cert.getIssuer()));
      if (x509crl != null && VerifyUtil.verifyByCRL(x509Cert, x509crl)) {
        throw new CodeException("C9002", "证书已经吊销");
      }
    }
  }

  @Override
  public String getPdfPageCount(byte[] pdf) {
    logger.info("获取PDF页数总和,开始");
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.getPdfPageCount.toString(), "获取PDF页数总和");
    boolean var3 = false;

    String var5;
    try {
      if (null == pdf || pdf.length == 0) {
        throw new CodeException("C3007", "PDF文档不能为空");
      }

      PrePdfReader prePdfReader = new PrePdfReader(pdf);
      int totalPage = prePdfReader.getPdfReader().getNumberOfPages();
      logger.info("获取PDF页数总和,结束");
      return "<Result><Code>200</Code><Message>successfully!</Message><PageCount>" + totalPage + "</PageCount></Result>";
    } catch (CodeException var10) {
      operationLog.setResult(10);
      logger.info("获取PDF页数总和接口发生异常", var10);
      var5 = "<Result><Code>" + var10.getCode() + "</Code><Message>" + var10.getMessage() + "</Message></Result>";
      return var5;
    } catch (Exception var11) {
      operationLog.setResult(10);
      logger.info("获取PDF页数总和发生异常", var11);
      if (var11.getMessage().contains("not found")) {
        var5 = "<Result><Code>C1010</Code><Message>没有找到相应的关键字</Message></Result>";
        return var5;
      }

      var5 = "<Result><Code>C0001</Code><Message>获取PDF页数总和接口发生异常</Message></Result>";
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return var5;
  }

  @Override
  public byte[] revokePdfSeal(byte[] pdf, int count) {
    logger.info("撤销PDf印章,开始");
    logger.info("count=" + count);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.getPdfPageCount.toString(), "撤销PDf印章");
    byte[] pdfResult = "".getBytes();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] var7;
    try {
      if (null != pdf && pdf.length != 0) {
        if (!StringUtil.checkNumber(String.valueOf(count), "0+")) {
          throw new CodeException("C3071", "需要撤销印章的个数只能输入非负整数");
        }

        ByteArrayInputStream is = new ByteArrayInputStream(pdf);
        cfca.com.itextpdf.text.pdf.PdfReader reader = new cfca.com.itextpdf.text.pdf.PdfReader(is);
        ArrayList<String> sigNames = reader.getAcroFields().getSignatureNames();
        int pdfSealNo = sigNames.size();
        logger.info("获取到的PDF文档内印章数量为：" + pdfSealNo);
        if (count > pdfSealNo) {
          throw new CodeException("C3070", "需要撤销印章的个数大于文档中印章总数");
        }

        if (count == 0) {
          count = pdfSealNo;
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(pdf);

        for(int i = 0; i < count; ++i) {
          DonePdfSeal.removeLastPdfSeal(bais, baos);
          if (i != count - 1) {
            bais = new ByteArrayInputStream(baos.toByteArray());
            baos.reset();
          }
        }

        logger.info("撤销PDf印章,结束");
        return pdfResult;
      }

      throw new CodeException("C3007", "PDF文档不能为空");
    } catch (CodeException var20) {
      CodeException ce = var20;
      operationLog.setResult(10);
      logger.info("撤销PDf印章接口发生异常", var20);

      try {
        var7 = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
      } catch (UnsupportedEncodingException var18) {
        var18.printStackTrace();
        return pdfResult;
      }
    } catch (Exception var21) {
      operationLog.setResult(10);
      logger.info("撤销PDf印章发生异常", var21);

      try {
        var7 = "<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>撤销PDf印章接口发生异常</ErrorMessage></Error>".getBytes("UTF-8");
        return var7;
      } catch (UnsupportedEncodingException var19) {
        var19.printStackTrace();
        return pdfResult;
      }
    } finally {
      pdfResult = baos.toByteArray();
      this.operationLogDao.insert(operationLog);
    }

    return var7;
  }
}
